package com.harveyh.cemax;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.harveyh.cemax.common.EActivity;
import com.harveyh.cemax.common.GloableData;
import com.harveyh.cemax.config.Preferences;
import com.harveyh.cemax.manager.DBManager;
import com.harveyh.cemax.manager.OtherDataDBManager;
import com.harveyh.cemax.manager.UtilsManager;
import com.harveyh.cemax.manager.ZipManager;

public class LoadingActivity extends EActivity {
	private Preferences pre;
	SharedPreferences msp;
	private ProgressDialog pdialog;
	
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        pre = Preferences.getInstance(getApplicationContext());
        msp = getSharedPreferences("mySP",Activity.MODE_PRIVATE);
        /** 该语句用于第一次执行数据库升级操作，不可删除 */
		DBManager db = DBManager.open(this);
		chushihua(getApplicationContext());
		
    }

	/** 初始化 */
	private void chushihua(final Context context) {
		new Thread() {
			public void run() {
				try {
					/** 判断SD卡数据库是否需要解压 */
					boolean isNeedInitSDCardData = false;
					if (UtilsManager.isSDCardAvailable()) {
						if (!ZipManager.checkFileAlmanacExists()) {// 数据库不存在
							isNeedInitSDCardData = true;
						} 
					}// end 监测SD卡
					if (isNeedInitSDCardData) {
						System.out.println("解压数据库文件...");
						ZipManager.extnativeZipFileList(context.getResources().getAssets().open("exam.zip"),GloableData.DB_DIR);
					}
					if (isNeedInitSDCardData||msp.getBoolean("isCEMAXFirstIn", true)) {
						handler.sendEmptyMessage(50);//loading...
						OtherDataDBManager db = new OtherDataDBManager(context);
						db.importDBFromDBFile();
						msp.edit().putBoolean("isCEMAXFirstIn", false).commit();
					} else {
						/** 显示启动画面 */
						Thread.sleep(1000);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				handler.sendEmptyMessage(1);
			}// run
		}.start();
	}// Chushihua
	
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (LoadingActivity.this.isFinishing()){
				return;
			}
			switch (msg.what) {
			case 1:
				if (pdialog!=null&&pdialog.isShowing()) {
					pdialog.cancel();
				}
				Intent in = new Intent(LoadingActivity.this,StartActivity.class);
				startActivity(in);
				LoadingActivity.this.finish();
				break;
			case 50:
				pdialog = new ProgressDialog(LoadingActivity.this);
				pdialog.setCanceledOnTouchOutside(false);
				pdialog.setMessage("正在加载数据...");
				pdialog.show();
				break;
			case 51:
				pdialog.cancel();
				break;
			default:
				break;
			}
		}
	};
    
}